package com.neusoft.elmboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.elmboot.Dto.UserDto;
import com.neusoft.elmboot.Vo.UserVo;
import com.neusoft.elmboot.common.constant.JwtClaimsConstant;
import com.neusoft.elmboot.common.exception.LoginFailedException;
import com.neusoft.elmboot.common.properties.JwtProperties;
import com.neusoft.elmboot.common.result.Result;
import com.neusoft.elmboot.common.utils.JwtUtil;
import com.neusoft.elmboot.po.UserEntity;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.service.impl.MyUserDetailServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/users")
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MyUserDetailServiceImpl userDetailService;


    /**
     * 用户登录
     * @param userDto
     * @return
     */
    @PostMapping(value = "/login")
    public Result login(@RequestBody UserDto userDto){
        String code = userDto.getCode();
        if (!userDto.getSource().equalsIgnoreCase("pc")){
            if (null == code || "".equals(code.trim())) {
                return Result.error("验证码不能为空！");
            }

            String codeRedis = (String)redisTemplate.opsForValue().get("elm:user:login:verityCode");
            if(!code.trim().equalsIgnoreCase(codeRedis)) {
                return Result.error("验证码出错：验证码过期或输入错误！");
            }
        }



        UserEntity user = userService.getByUserName(userDto);
        if (user==null){
            throw new LoginFailedException("用户名不存在");
        }
        UserVo userVo  = userService.login(userDto);
        BeanUtils.copyProperties(user,userVo);
        //Map<String,Object> map = new HashMap();
        //map.put(JwtClaimsConstant.USER_ID,userVo.getUserId());
        //String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);
        //userVo.setToken(token);


        return Result.success(userVo);

    }

    @GetMapping("/info")
    public ResponseEntity<TestResponse> login(String token) {
        TestResponse response = new TestResponse();
        TestData data = new TestData();
        if(token !="admin-token"){
            response.setCode(20000);
            data.setRoles(Arrays.asList("admin"));
            data.setIntroduction("I am a super administrator");
//            data.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            data.setName("Super Admin");
            response.setData(data);}

        return ResponseEntity.ok(response);
    }

    /**
     * 用户分页查询
     * @param page
     * @param limit
     * @param userId
     * @param userName
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("用户分页查询")
    public Result<Page> page(Integer page,Integer limit,String userId,String userName){
        log.info("用户分页查询,{},{},{},{}",page,limit,userId,userName);
        Page pageInfo = new Page(page,limit);
        LambdaQueryWrapper<UserEntity> lqw = new LambdaQueryWrapper();
        lqw.like(userName!=null, UserEntity::getUserName,userName);
        lqw.eq(userId!=null,UserEntity::getUserId,userId);

        userService.page(pageInfo,lqw);
        return Result.success(pageInfo);


    }

    /**
     *
     * @param userDto
     * @return
     */
    @ApiOperation("添加用户")
    @PostMapping
    public Result save(@RequestBody UserDto userDto){
        log.info("添加用户:{}",userDto);
        userService.add(userDto);

        return Result.success();
    }

    /**
     * 删除用户id
     * @param id
     * @return
     */
    @ApiOperation("删除用户id")
    @DeleteMapping
    public Result remove(String id){
        log.info("删除用户id:{}",id);
        userService.removeById(id);
        return Result.success();

    }

    /**
     * 更新用户
     * @param userDto
     * @return
     */
    @PutMapping
    @ApiOperation("更新用户")
    public Result update(@RequestBody UserDto userDto){
        log.info("更新用户, {}",userDto.toString());
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDto,userEntity);
        userService.updateById(userEntity);
        return Result.success();

    }

    /**
     * 更新用户
     * @param id
     * @return
     */
    @ApiOperation("用户回显")
    @GetMapping("/detail")
    public Result<UserVo> getById(String id){
        log.info("用户回显, {}",id);
        UserEntity userEntity = userService.getById(id);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userEntity,userVo);

        return Result.success(userVo);

    }

    @PostMapping("/logout")
    public Result logout(){
        return Result.success();
    }



}

@Data
class TestResponse {
    private int code;
    private TestData data;

    // getters, setters...
}

@Data
class TestData {
    private List<String> roles;
    private String introduction;
    private String avatar;
    private String name;
}






